package com.gupaoedu.interceptor;


import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;

import java.sql.Statement;
import java.util.Properties;

/**
 * 2020/2/26
 * created by chenpp
 * 拦截 StatementHandler的query/update,这是最终执行SQL的地方
 */
@Intercepts(
        {@Signature(type = StatementHandler.class,method = "query",
        args = {Statement.class, ResultHandler.class})
                ,@Signature(type = StatementHandler.class,method = "update",
        args = {Statement.class})
                ,@Signature(type = StatementHandler.class,method = "batch",
                args = {Statement.class})
})
public class CPSQLLogInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Long start = System.currentTimeMillis();
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        String sql = statementHandler.getBoundSql().getSql();
        Object obj = statementHandler.getParameterHandler().getParameterObject();
        System.out.println("执行的SQL语句："+sql+" ,参数为:" + obj);
        try {
            return invocation.proceed();
        }finally {
            long end = System.currentTimeMillis();
            System.out.println("SQL执行耗时：" + (end-start) +"ms");
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target,this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
